import { nextTick } from 'vue'
import Icon from '../components/icon/index.vue'
import * as elIcons from '@element-plus/icons-vue'
import { i18n } from '../lang'
import { useSiteConfig } from '../store/siteConfig'
import router from '../router/index'
import { useTitle } from '@vueuse/core'
export function registerIcons(app) {
    /*
     * 全局注册 Icon
     * 使用方式: <Icon name="name" size="size" color="color" />
     * 详见<待完善>
     */
    app.component('Icon', Icon);

    /*
     * 全局注册element Plus的icon
     */
    const icons = elIcons;
    for (const i in icons) {
        app.component(`el-icon-${icons[i].name}`, icons[i]);
    }
    //app.use(Icon);
}

/**
 * 是否是外部链接
 * @param path
 */
export function isExternal(path) {
    return /^(https?|ftp|mailto|tel):/.test(path)
}

/**
 * 获取资源完整地址
 * @param relativeUrl 资源相对地址
 * @param domain 指定域名
 */
export const fullUrl = (relativeUrl, domain = '') => {
    const siteConfig = useSiteConfig()
    if (!domain) {
        domain = siteConfig.cdnUrl ? siteConfig.cdnUrl : window.location.hostname
    }
    if (!relativeUrl) return domain

    const regUrl = new RegExp(/^http(s)?:\/\//)
    const regexImg = new RegExp(/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i)
    if (!domain || regUrl.test(relativeUrl) || regexImg.test(relativeUrl)) {
        return relativeUrl
    }
    return domain + relativeUrl
}

/**
 * 根据路由 meta.title 设置浏览器标题
 */
export function setTitleFromRoute() {
    if (typeof router.currentRoute.value.meta.title != 'string') {
        return
    }
    nextTick(() => {
        let webTitle = ''
        if ((router.currentRoute.value.meta.title).indexOf('pagesTitle.') === -1) {
            webTitle = router.currentRoute.value.meta.title
        } else {
            webTitle = i18n.global.t(router.currentRoute.value.meta.title)
        }
        const title = useTitle()
        const siteConfig = useSiteConfig()
        title.value = `${webTitle}${siteConfig.siteName ? ' - ' + siteConfig.siteName : ''}`
    })
}